using System;
using System.Data;
using PCSComMaterials.Inventory.BO;
using PCSComSale.Order.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;

using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
using PCSComUtils.DataContext;
using PCSComUtils.DataAccess;
using System.Text;
using System.Transactions;
using System.Linq;

namespace PCSComSale.Order.BO
{
    public class SOCancelCommitmentBO //: ISOCancelCommitmentBO
    {
        private const string THIS = "PCSComSale.Order.BO.SOConfirmPacklistBO";
        public SOCancelCommitmentBO()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public void Add(object pObjectDetail)
        {
            // TODO:  Add SOConfirmPacklistBO.Add implementation

        }

        public void Delete(object pObjectVO)
        {
            // TODO:  Add SOConfirmPacklistBO.Delete implementation

        }

        public DataSet List()
        {
            return null;
        }

        public object GetObjectVO(int pintID, string VOclass)
        {
            // TODO:  Add SOConfirmPacklistBO.GetObjectVO implementation
            return null;
        }

        public void Update(object pObjectDetail)
        {
            // TODO:  Add SOConfirmPacklistBO.Update implementation

        }

        public void UpdateDataSet(DataSet dstData)
        {
            // TODO:  Add SOConfirmPacklistBO.UpdateDataSet implementation

        }

        //**************************************************************************              
        ///    <Description>
        ///       Get SaleOrderMaster by code
        ///    </Description>
        ///    <Inputs>
        ///		  int psrtCode : SaleOrderMaster Code 
        ///    </Inputs>
        ///    <Outputs>
        ///    </Outputs>
        ///    <Returns>
        ///       object
        ///    </Returns>
        ///    <Authors>
        ///       TuanDm
        ///    </Authors>
        ///    <History>
        ///       Friday, February 25, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public object GetObjectSaleOrderMaster(string psrtCode)
        {
            try
            {
                SO_SaleOrderMasterDS dsSaleOrderMasterDS = new SO_SaleOrderMasterDS();
                return dsSaleOrderMasterDS.GetObjectVO(psrtCode);
            }
            catch (PCSDBException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //**************************************************************************              
        ///    <Description>
        ///       Search all items of sale order
        ///    </Description>
        ///    <Inputs>
        ///		  int pintSaleOrderMasterID : SaleOrderID 
        ///    </Inputs>
        ///    <Outputs>
        ///    </Outputs>
        ///    <Returns>
        ///       DataTable
        ///    </Returns>
        ///    <Authors>
        ///       TuanDm
        ///    </Authors>
        ///    <History>
        ///       Friday, February 25, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public DataSet ListCancelable(int pintSaleOrderMasterID)
        {
            try
            {
                SO_CommitInventoryDetailDS dsCommitInventory = new SO_CommitInventoryDetailDS();
                return dsCommitInventory.ListCancelable(pintSaleOrderMasterID);
            }
            catch (PCSDBException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //**************************************************************************              
        ///    <Description>
        ///       Auto delete all SaleOrderMaster which is have no item in CommitInventoryDetail
        ///    </Description>
        ///    <Inputs>
        ///    </Inputs>
        ///    <Outputs>
        ///    </Outputs>
        ///    <Returns>
        ///    </Returns>
        ///    <Authors>
        ///       TuanDm
        ///    </Authors>
        ///    <History>
        ///       Friday, February 25, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        private bool DeleteCommitInvertoryMaster(PCSDataContext db)
        {
            bool ret = true;
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" Delete ");
            strSql.Append(" From " + SO_CommitInventoryMasterTable.TABLE_NAME);
            strSql.Append(" Where (Select count (*)");
            strSql.Append(" From " + SO_CommitInventoryDetailTable.TABLE_NAME);
            strSql.Append(" Where " + SO_CommitInventoryDetailTable.TABLE_NAME + "." + SO_CommitInventoryDetailTable.COMMITINVENTORYMASTERID_FLD + " = " + SO_CommitInventoryMasterTable.TABLE_NAME + "." + SO_CommitInventoryMasterTable.COMMITINVENTORYMASTERID_FLD + ") = 0");
            try
            {
                if (db == null) db = new PCSDataContext(Utils.Instance.ConnectionString);
                db.ExecuteCommand(strSql.ToString());
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                ret = false;
                throw ex;
            }
            return ret;

        }
        private bool DeletePackListMaster(PCSDataContext db)
        {
            bool ret = true;
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" Delete ");
            strSql.Append("From " + SO_PackListMasterTable.TABLE_NAME);
            strSql.Append(" Where (Select count (*)");
            strSql.Append(" From " + SO_PackListDetailTable.TABLE_NAME);
            strSql.Append(" Where " + SO_PackListDetailTable.TABLE_NAME + "." + SO_PackListDetailTable.PACKLISTMASTERID_FLD + " = " + SO_PackListMasterTable.TABLE_NAME + "." + SO_PackListMasterTable.PACKLISTMASTERID_FLD + ") = 0");
            try
            {
                if (db == null) db = new PCSDataContext(Utils.Instance.ConnectionString);
                db.ExecuteCommand(strSql.ToString());
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                ret = false;
                throw ex;
            }
            return ret;
        }

        private void AutoDeleteCommitInventoryMaster()
        {
            try
            {
                SO_CommitInventoryMasterDS dsCommitInventory = new SO_CommitInventoryMasterDS();
                dsCommitInventory.AutoDeleteCommitMaster();
            }
            catch (PCSDBException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //**************************************************************************              
        ///    <Description>
        ///       Auto delete all PackListMaster which is have no item in PackListDetail
        ///    </Description>
        ///    <Inputs>
        ///    </Inputs>
        ///    <Outputs>
        ///    </Outputs>
        ///    <Returns>
        ///    </Returns>
        ///    <Authors>
        ///       TuanDm
        ///    </Authors>
        ///    <History>
        ///       Tuesday, Mar 08, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        private void AutoDeletePackListMaster()
        {
            try
            {
                SO_PackListMasterDS dsPackList = new SO_PackListMasterDS();
                dsPackList.AutoDeletePackListMaster();
            }
            catch (PCSDBException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //**************************************************************************              
        ///    <Description>
        ///       
        ///    </Description>
        ///    <Inputs>
        ///    </Inputs>
        ///    <Outputs>
        ///    </Outputs>
        ///    <Returns>
        ///       void
        ///    </Returns>
        ///    <Authors>
        ///       TuanDm
        ///    </Authors>
        ///    <History>
        ///       Friday, March 4, 2005
        ///    </History>
        ///    <Notes>
        ///    </Notes>
        //**************************************************************************
        //[AutoComplete(true)]
        public void CancelCommitment(DataTable pdtbData, int pintCCNID)
        {
            const string Cancel = "Cancel", True = "True";
            try
            {
                UtilsBO boUtils = new UtilsBO();
                DateTime dSeverDate = boUtils.GetDBDate();
                using (var trans = new TransactionScope())
                {
                    using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                    {
                        try
                        {                           
                            foreach (DataRow drowData in pdtbData.Rows)
                            {
                                if ((drowData.RowState == DataRowState.Modified) && (drowData[Cancel].ToString() == True))
                                {
                                    decimal decRate = boUtils.GetUMRate(int.Parse(drowData[SO_CommitInventoryDetailTable.SELLINGUMID_FLD].ToString()), int.Parse(drowData[ITM_ProductTable.STOCKUMID_FLD].ToString()));
                                    int intProductID = int.Parse(drowData[SO_CommitInventoryDetailTable.PRODUCTID_FLD].ToString());
                                    int intSOMasterID = int.Parse(drowData[SO_CommitInventoryDetailTable.COMMITINVENTORYMASTERID_FLD].ToString());
                                    int intSODetailID = int.Parse(drowData[SO_CommitInventoryDetailTable.COMMITINVENTORYDETAILID_FLD].ToString());
                                    Decimal decQuantity = Decimal.Parse(drowData[SO_CommitInventoryDetailTable.COMMITQUANTITY_FLD].ToString());
                                    int intMasLocID = 0;
                                    if (drowData[SO_CommitInventoryDetailTable.MASTERLOCATIONID_FLD].ToString() != string.Empty)
                                    {
                                        intMasLocID = int.Parse(drowData[SO_CommitInventoryDetailTable.MASTERLOCATIONID_FLD].ToString());
                                    }
                                    int intLocationID = 0;
                                    if (drowData[SO_CommitInventoryDetailTable.LOCATIONID_FLD].ToString() != string.Empty)
                                    {
                                        intLocationID = int.Parse(drowData[SO_CommitInventoryDetailTable.LOCATIONID_FLD].ToString());
                                    }
                                    int intBinID = 0;
                                    if (drowData[SO_CommitInventoryDetailTable.BINID_FLD].ToString() != string.Empty)
                                    {
                                        intBinID = int.Parse(drowData[SO_CommitInventoryDetailTable.BINID_FLD].ToString());
                                    }
                                    MST_TransactionHistory voTransaction = new MST_TransactionHistory();
                                    voTransaction.CCNID = pintCCNID;
                                    voTransaction.MasterLocationID = intMasLocID;
                                    voTransaction.ProductID = intProductID;
                                    voTransaction.LocationID = intLocationID;
                                    voTransaction.BinID = intBinID;
                                    voTransaction.RefMasterID = intSOMasterID;
                                    voTransaction.RefDetailID = intSODetailID;
                                    voTransaction.PostDate = voTransaction.TransDate = dSeverDate;
                                    voTransaction.Quantity = decQuantity * decRate;
                                    voTransaction.TranTypeID = db.MST_TranTypes.SingleOrDefault(e => e.Code == TransactionType.CANCEL_COMMITMENT).TranTypeID;
                                    voTransaction.StockUMID = (int)drowData[SO_CommitInventoryDetailTable.STOCKUMID_FLD];
                                    new InventoryUtilsBO().UpdateSubstractCommitQtyAll(pintCCNID, intMasLocID, intLocationID, intBinID, intProductID, decQuantity * decRate, string.Empty, string.Empty, db);
                                    //dsCommitDetail.Delete(int.Parse(drowData[SO_CommitInventoryDetailTable.COMMITINVENTORYDETAILID_FLD].ToString()));
                                    DeleteCommitDetail(int.Parse(drowData[SO_CommitInventoryDetailTable.COMMITINVENTORYDETAILID_FLD].ToString()), db);
                                    DeleteByCommitInventoryDetail(int.Parse(drowData[SO_CommitInventoryDetailTable.COMMITINVENTORYDETAILID_FLD].ToString()), db);
                                    //new InventoryUtilsBO().SaveTransactionHistory(TransactionType.CANCEL_COMMITMENT, (int)PurposeEnum.CancelCommitment, voTransaction);
                                    //string[] strComment = new string[1];
                                    new InventoryUtilsBO().SaveTransactionHis(TransactionType.CANCEL_COMMITMENT, (int)PurposeEnum.CancelCommitment, voTransaction, db, string.Empty);
                                }
                            }
                            DeleteCommitInvertoryMaster(db);
                            DeletePackListMaster(db);
                        }
                        catch (Exception ex)
                        { Transaction.Current.Rollback(ex); }
                        finally
                        { trans.Complete(); }
                    }
                }
            }
            catch (PCSDBException ex)
            {
                throw ex;
            }
            catch (PCSException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool DeleteCommitDetail(int iCommitInventoryDetailID, PCSDataContext db)
        {
            bool ret = true;
            const string METHOD_NAME = THIS + ".DeleteByCommitInventoryDetail()";
            string strSql = String.Empty;
            strSql = " DELETE " + SO_CommitInventoryDetailTable.TABLE_NAME + " WHERE  " + SO_CommitInventoryDetailTable.COMMITINVENTORYDETAILID_FLD + "=" + iCommitInventoryDetailID.ToString();
            try
            {
                if (db == null) db = new PCSDataContext(Utils.Instance.ConnectionString);
                db.ExecuteCommand(strSql);
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                ret = false;
                throw ex;
            }
            return ret;
        }
        //cuonglv
        public bool DeleteByCommitInventoryDetail(int iCommitInventoryDetailID, PCSDataContext db)
        {
            bool ret = true;
            const string METHOD_NAME = THIS + ".DeleteByCommitInventoryDetail()";
            string strSql = String.Empty;
            strSql = "DELETE " + SO_PackListDetailTable.TABLE_NAME + " WHERE  " + SO_PackListDetailTable.COMMITINVENTORYDETAILID_FLD + "=" + iCommitInventoryDetailID.ToString();
            try
            {
                if (db == null) db = new PCSDataContext(Utils.Instance.ConnectionString);
                db.ExecuteCommand(strSql);
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                ret = false;
                throw ex;
            }
            return ret;
        }
        //[AutoComplete(true)]
        public string GetBuyingLocName(int pintID)
        {
            try
            {
                MST_PartyLocationDS dsParty = new MST_PartyLocationDS();
                return ((MST_PartyLocationVO)dsParty.GetObjectVO(pintID)).Code;
            }
            catch (PCSDBException ex)
            {
                throw ex;
            }
            catch (PCSException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
